package com.zbzly.video.service;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.*;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

@Service
@Slf4j
public class ImageService {

    public void convert2Image() {
        avutil.av_log_set_level(avutil.AV_LOG_INFO);
        FFmpegLogCallback.set();
        int i = 0;
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("D:\\Temp\\video\\tmp.mp4")) {
            grabber.start();
            // 获取视频帧率
            double frameRate = grabber.getFrameRate();
            System.out.println("frameRate = " + frameRate);
            try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("D:\\Temp\\video\\image\\image-%3d.jpeg",
                    grabber.getImageWidth(), grabber.getImageHeight())) {
                recorder.setFormat("image2");
                recorder.setFrameRate(grabber.getFrameRate());
                recorder.start();
                Frame frame;
                while ((frame = grabber.grabImage()) != null) {
                    // 每十帧转换一次
                    if (i % 10 == 0) {
                        recorder.recordImage(frame.imageWidth, frame.imageHeight, frame.imageDepth, frame.imageChannels, frame.imageStride,
                                avutil.AV_PIX_FMT_NONE, frame.image);
                    }
                    i++;
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public void convert2ImageGrabber() {
        avutil.av_log_set_level(avutil.AV_LOG_INFO);
        FFmpegLogCallback.set();
        int i = 0;
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("D:\\Temp\\video\\tmp.mp4")) {
            grabber.start();
            // 获取视频帧率
            double frameRate = grabber.getFrameRate();
            System.out.println("frameRate = " + frameRate);
            Frame frame;

            while ((frame = grabber.grabImage()) != null) {
                try (Java2DFrameConverter converter = new Java2DFrameConverter()) {
                    BufferedImage bufferedImage = converter.convert(frame);
                    String formatFile = String.format("D:\\Temp\\video\\convert\\image-%d.jpeg", i);
                    File file = new File(formatFile);
                    ImageIO.write(bufferedImage, "jpg", file);
                }
                i++;
            }
            System.out.println(i);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
